package spring.boot.adminx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.list.TreeList;
import org.springframework.stereotype.Service;
import spring.boot.adminx.mapper.SysMenuMapper;
import spring.boot.adminx.model.SysMenu;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {

    public List<SysMenu> selectTreeMenus(List<String> menuIds) {
        QueryWrapper<SysMenu> oneWrapper = new QueryWrapper<>();
        oneWrapper.eq("level",1);
        List<SysMenu> menus = list(oneWrapper);
        for (int i = 0; i < menus.size(); i++) {
            QueryWrapper<SysMenu> twoWrapper = new QueryWrapper<>();
            twoWrapper.eq("level",2);
            twoWrapper.eq("p_id",menus.get(i).getId());
            List<SysMenu> twoList = list(twoWrapper);
            if (!twoList.isEmpty()){
                menus.get(i).setIsLeaf(false);
                menuIds.remove(menus.get(i).getId());
            }
            for (int j = 0; j < twoList.size(); j++) {
                QueryWrapper<SysMenu> threeWrapper = new QueryWrapper<>();
                threeWrapper.eq("level",3);
                threeWrapper.eq("p_id",twoList.get(j).getId());
                List<SysMenu> threeList = list(threeWrapper);
                if (!threeList.isEmpty()){
                    twoList.get(j).setIsLeaf(false);
                    menuIds.remove(twoList.get(j).getId());
                }
                twoList.get(j).setChildren(threeList);
            }
            menus.get(i).setChildren(twoList);
        }
        return menus;
    }

    public List<SysMenu> selectLeftMenu(long userId) {
        List<SysMenu> oneList = baseMapper.selectLeftByLevel(userId,1,0L);
        for (int i = 0; i < oneList.size(); i++) {
            Long pId = oneList.get(i).getId();
            List<SysMenu> twoList = baseMapper.selectLeftByLevel(userId,2,pId);
            oneList.get(i).setChildren(twoList);
        }
        return oneList;

    }

    /** 菜单列表查询 */
    public List<SysMenu> selectTreeList() {
        //递归查询所有菜单
        return baseMapper.selectAllMenus();
    }
}
